package com.sso.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.regex.Pattern;

/**
 * 类 {@code XssHttpServletRequestWrapper} XSS攻击过滤实现逻辑 <br> XSS攻击过滤实现逻辑.
 *
 * <p>详细描述
 * <p>
 *
 * @author <a href="mailto:lz2392504@gmail.com">CN華少</a>
 * @see  HttpServletRequestWrapper
 * @since v1.0.0
 */
public class XssHttpServletRequestWrapper extends HttpServletRequestWrapper {


    HttpServletRequest orgRequest = null;

    public XssHttpServletRequestWrapper(HttpServletRequest request) {
        super(request);
        orgRequest = request;
    }

    /**
     * 覆盖getParameter方法，将参数名和参数值都做xss & sql过滤。<br/>
     * 如果需要获得原始的值，则通过super.getParameterValues(name)来获取<br/>
     * getParameterNames,getParameterValues和getParameterMap也可能需要覆盖
     */
    @Override
    public String getParameter(String name) {
        String value = super.getParameter(xssEncode(name));
        if (value != null) {
            value = xssEncode(value);
        }
        return value;
    }

    /**
     * 覆盖getHeader方法，将参数名和参数值都做xss & sql过滤。<br/>
     * 如果需要获得原始的值，则通过super.getHeaders(name)来获取<br/>
     * getHeaderNames 也可能需要覆盖
     */
    @Override
    public String getHeader(String name) {

        String value = super.getHeader(xssEncode(name));
        if (value != null) {
            value = xssEncode(value);
        }
        return value;
    }

    /**
     * 将容易引起xss & sql漏洞的半角字符直接替换成全角字符
     *
     * @param s
     * @return
     */
    private static String xssEncode(String s) {
        if (s == null || s.isEmpty()) {
            return s;
        }else{
            s = stripXSSAndSql(s);
        }
        StringBuilder sb = new StringBuilder(s.length() + 16);
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            switch (c) {
                case '>':
                    sb.append("＞");// 转义大于号
                    break;
                case '<':
                    sb.append("＜");// 转义小于号
                    break;
                case '\'':
                    sb.append("＇");// 转义单引号
                    break;
                case '\"':
                    sb.append("＂");// 转义双引号
                    break;
                case '&':
                    sb.append("＆");// 转义&
                    break;
                case '#':
                    sb.append("＃");// 转义#
                    break;
                default:
                    sb.append(c);
                    break;
            }
        }
        return sb.toString();
    }

    /**
     * 获取最原始的request
     *
     * @return
     */
    public HttpServletRequest getOrgRequest() {
        return orgRequest;
    }

    /**
     * 获取最原始的request的静态方法
     *
     * @return
     */
    public static HttpServletRequest getOrgRequest(HttpServletRequest req) {
        if (req instanceof XssHttpServletRequestWrapper) {
            return ((XssHttpServletRequestWrapper) req).getOrgRequest();
        }

        return req;
    }


    private static Pattern XSSAndSql_PATTERN1 = Pattern.compile("<[\r\n| | ]*script[\r\n| | ]*>(.*?)</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
    private static Pattern XSSAndSql_PATTERN2 = Pattern.compile("src[\r\n| | ]*=[\r\n| | ]*[\\\"|\\\'](.*?)[\\\"|\\\']", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    private static Pattern XSSAndSql_PATTERN3 = Pattern.compile("</[\r\n| | ]*script[\r\n| | ]*>", Pattern.CASE_INSENSITIVE);
    private static Pattern XSSAndSql_PATTERN4 = Pattern.compile("<[\r\n| | ]*script(.*?)>", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    private static Pattern XSSAndSql_PATTERN5 = Pattern.compile("eval\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    private static Pattern XSSAndSql_PATTERN6 = Pattern.compile("e-xpression\\((.*?)\\)", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    private static Pattern XSSAndSql_PATTERN7 = Pattern.compile("javascript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
    private static Pattern XSSAndSql_PATTERN8 = Pattern.compile("vbscript[\r\n| | ]*:[\r\n| | ]*", Pattern.CASE_INSENSITIVE);
    private static Pattern XSSAndSql_PATTERN9 = Pattern.compile("onload(.*?)=", Pattern.CASE_INSENSITIVE | Pattern.MULTILINE | Pattern.DOTALL);
    //过滤SQL关键词master、truncate、insert、select、delete、update、declare、alert、create、drop、and、%27、'、%6F、%72、or、%3b、%2031   |(%3[Bb])|(%2031
    private static String SQL_RE="([Mm][Aa][Ss][Tt][Ee][Rr])|([Tt][Rr][Uu][Nn][Cc][Aa][Tt][Ee])|([Ii][Nn][Ss][Ee][Rr][Tt])|([Ss][Ee][Ll][Ee][Cc][Tt])|([Dd][Ee][Ll][Ee][Tt][Ee])|([Uu][Pp][Dd][Aa][Tt][Ee])|([Dd][Ee][Cc][Ll][Aa][Rr][Ee])|([Aa][Ll][Ee][Rr][Tt])|([Cc][Rr][Ee][Aa][Tt][Ee])|([Dd][Rr][Oo][Pp])|([Aa][Nn][Dd])|(%27|')|((%6[Ff]|%72)|([Oo][Rr])).*?";
    //后缀参数注释：不区分大小写、多线程、匹配所有
    private static Pattern XSSAndSql_PATTERN10 = Pattern.compile(SQL_RE, Pattern.CASE_INSENSITIVE| Pattern.MULTILINE| Pattern.DOTALL);

    /**
     *
     * 防止xss跨脚本攻击（替换，根据实际情况调整）
     */

    public static String stripXSSAndSql(String value) {
        if (value != null) {
            //防止脚本注入
            // Avoid anything between script tags
            value = XSSAndSql_PATTERN1.matcher(value).replaceAll("");
            // Avoid anything in a src="http://www.yihaomen.com/article/java/..." type of e-xpression
            value = XSSAndSql_PATTERN2.matcher(value).replaceAll("");
            // Remove any lonesome </script> tag
            value = XSSAndSql_PATTERN3.matcher(value).replaceAll("");
            // Remove any lonesome <script ...> tag
            value = XSSAndSql_PATTERN4.matcher(value).replaceAll("");
            // Avoid eval(...) expressions
            value = XSSAndSql_PATTERN5.matcher(value).replaceAll("");
            // Avoid e-xpression(...) expressions
            value = XSSAndSql_PATTERN6.matcher(value).replaceAll("");
            // Avoid javascript:... expressions
            value = XSSAndSql_PATTERN7.matcher(value).replaceAll("");
            // Avoid vbscript:... expressions
            value = XSSAndSql_PATTERN8.matcher(value).replaceAll("");
            // Avoid onload= expressions
            value = XSSAndSql_PATTERN9.matcher(value).replaceAll("");

            //防止SQL注入
            //value = XSSAndSql_PATTERN10.matcher(value).replaceAll("");

        }
        return value;
    }
}
